<?php


namespace App\Console\Commands;


use App\Utils\Code;
use App\Utils\Server\SocketHandle;

class WebSocketCommand extends \webSocket\Commands\WebSocketCommand
{

    /**
     * 启动命令
     * @var string
     */
    protected $signature = "websocket {mode?}";

    /**
     * 命令描述
     * @var string
     */
    protected $description = "WebSocket Service | start | restart | stop | status";

    /**
     * 设置 WebSocket 处理程序
     * @return string|void
     */
    protected function getBindClass()
    {
        return SocketHandle::class;
    }

    /**
     * 获取 WebSocket 读取配置 默认websocket.php文件
     * @return string
     */
    protected function getConfig()
    {
        return "websocket"; // TODO: Change the autogenerated stub
    }

    /**
     * 执行命令
     * @return mixed|void
     * @throws \Exception
     */
    public function handle()
    {
        try {
            $mode = $this->argument('mode');
            if ($mode == 'started') {
                parent::handle(); // TODO: Change the autogenerated stub
            } elseif ($mode == 'start') {
                popen("nohup php artisan websocket started &", 'r');
            } elseif ($mode == 'restart') {
                exec("ps aux|grep websocket|grep -v grep|awk '{print $2}'|xargs kill -TERM && nohup php artisan websocket started");
            } elseif ($mode == 'stop') {
                exec("ps aux|grep websocket|grep -v grep|awk '{print $2}'|xargs kill -TERM");
            } elseif ($mode == 'status') {
                exec("lsof -i:9501|awk 'NR==2{print $2}'", $output);
                $res = json_decode(json_encode($output, JSON_UNESCAPED_UNICODE), true);
                echo ($res ? 'open' : 'close') . PHP_EOL;
            } else {
                echo 'websocket: start | restart | stop | status';
            }
        } catch (\Exception $exception) {
            Code::exceptionLog($exception);
            echo $exception->getMessage();
        }
    }
}
